<template>
  <div class='coin'>
    <van-nav-bar title="金币"
                 left-text=""
                 left-arrow
                 @click-left="onClickLeft">
    </van-nav-bar>
    <div class='top'>
      <p>余额</p>
      <p><span>¥</span> {{moneyown}}</p>
      <button @click='showRecharge'>立即充值</button>
    </div>
    <div class='title'>
      <span class='hed'>金币流水明细</span>
    </div>
    <span class="noData" v-if="recordslist.length === 0">暂无数据</span>
    <van-list v-model="loading"
              :finished="finished"
              @load="onLoad">
      <ul class='list'>
        <li v-for="item in recordslist"
            :key="item.id">
          <div>
            <!-- <input type='checkbox' /> 2019-05-06 12:02:30 -->
            <!--<input @click="handleCheck(item.id)" type='checkbox'/>-->
            <span>{{item.pubtime | moment}}</span>
          </div>
          <div class='bet'>
            <span>{{item.subject}}</span>
            <span>{{item.paycost}}</span>
          </div>
        </li>
      </ul>
      <!--<button class='del' @click="handledelete">删除</button>-->
    </van-list>

    <!-- 弹窗 -->
    <van-popup v-model="show"
               get-container="body"
               :round=true
               :style="{ width: '80%',padding:'10px',top:'37%' }">
      <h3 class='coin-title'>金币充值</h3>
      <div class='bet'
           @click='topType'>
        <span>支付方式 :</span>
        <p>
          <span>{{pay}}</span>
          <img src="../../../static/index/right.png"
               alt="">
        </p>
      </div>
      <div class='Recharge'>
        <span>充值数量 :</span>
        <input type="number"
               v-model="count"
               placeholder="请输入充值金币的数量">
      </div>
      <div class='Recharge'>
        <span>金额 :</span>
        <input type="number"
               v-model.number="FilterStick"
               placeholder="" disabled>
      </div>
      <button class='config' @click="handleWxPay">确认提交置顶</button>
    </van-popup>
    <!-- 选项 -->
    <van-popup v-model="showType">
      <van-picker show-toolbar
                  title="支付方式"
                  :columns="type"
                  @cancel="onCancel"
                  @confirm="onConfirm">
      </van-picker>
    </van-popup>
  </div>
</template>
<script>
  import {getStore, setStore} from '@/config/mUtils'
  import md5 from 'js-md5'

  export default {
    name: 'coin',
    data() {
      return {
        loading: false,
        finished: true,
        moneyown: '',
        result: [],
        recordslist: [],
        checkboxlist: [],
        show: false,
        showType: false,
        type: ['微信'],
        pay: '微信',
        count: '',
        money: '',
        nofifyId: '' //回调ID
      }
    },
    computed: {
      /**
       * @return {number}
       */
      FilterStick() {
        return this.money = (this.count * 10) / 1000
      }
    },
    methods: {
      initDate() {
        var params = this.qs.stringify({
          "token": getStore("token")
        })

        this.$axios.post('user/records', params).then((res) => {
          if ( res.data.status === 1 ) {
            this.recordslist = res.data.data
          }
        })


        this.$axios.post('user/info', this.qs.stringify({
          "token": getStore("token"),
        })).then((res) => {
          this.moneyown = res.data.data.money_own
        })

      },
      //唤起微信支付
      handleWxPay() {
        var _this = this;

        let pattern = /^[1-9]+(.[0-9]{0,9})?$/;
        if ( !pattern.test(this.count) ) {
          this.$toast.fail('请检查输入是否为整数!')
          // this.count = ''
          return
        }

        this.$axios.post('user/prepay', this.qs.stringify({
          "token": getStore("token"),
          "money": this.FilterStick,
          "type": "tenpay",
          "count": this.count,
        })).then((res) => {
          if ( res.data.status === 1 ) {

            var handleDate = res.data.data

            this.nofifyId = handleDate.nofify_id

            this.$toast.success(res.data.message)

            //调取微信
            var stringA = `appid=${handleDate.appId}&noncestr=${handleDate.nonceStr}&package=${handleDate.package}&partnerid=${handleDate.mch_id}&prepayid=${handleDate.prepay_id}&timestamp=${handleDate.timeStamp}`
            var stringSignTemp = stringA + "&key=265cfd0617c88cbb0847e224106d6d81";
            var sign = md5(stringSignTemp).toUpperCase();      // 为安全考虑，sign计算放到服务端，可以通过ajax传递给APP端
            var wxPay = api.require('wxPay');
            var params = {
              apiKey: res.data.data.appId, //微信开放平台审核通过的应用APPID
              orderId: res.data.data.prepay_id, //订单号
              mchId: res.data.data.mch_id, //商家和微信合作的 id 号，审核通过后微信服务器会发送到商家邮箱
              nonceStr: res.data.data.nonceStr, //随机字符串，防重发
              timeStamp: res.data.data.timeStamp, //时间戳同上
              package: res.data.data.package, //扩展字段 可选项
              sign: sign, //商家根据微信开放平台文档对数据做的签名
            }
            wxPay.payOrder(params, function (ret, err) {
              // console.log(ret)
              if ( ret.status ) {
                //支付成功,给予用户提示。
                _this.$toast.success('支付成功')
                _this.handleSusce()
              } else {
                _this.$toast.fail('支付失败')
              }
            });
          } else {
            // this.$toast.fail(res.data.message)
          }
        })
      },
      //成功回调
      handleSusce() {
        //支付成功后告知服务器
        //nofifyId
        this.$axios.post('user/notify', this.qs.stringify({
          "token": getStore("token"),
          "notify": this.nofifyId,
        })).then((res) => {
          // console.log(res, '回调调用成功')
          this.initDate()
        })
      },
      onClickLeft() {
        this.$router.go(-1)
      },
      onLoad() {
        this.$axios.post('user/records', params).then((res) => {
          // console.log(res)
        })
      },
      topType() {
        this.showType = true
      },
      onCancel() {
        this.showType = false
      },
      onConfirm() {
        this.showType = false
      },
      showRecharge() {
        this.show = true
      }
    },
    created() {
      this.initDate()
    }
  }
</script>
<style lang="scss" scoped>
  @import "../../../static/css/user/coin.scss";

  .coin {
    background-color: #f0f0f0;
  }

  .coin-title {
    text-align: center;
    font-weight: 800;
    font-size: 32px;
    margin-bottom: 30px;
  }

  .van-popup--center.van-popup--round > > > .bet {
    font-size: 28px;
    padding: 12px;
    border-bottom: 2px solid #e4e4e4;
    margin-bottom: 20px;
  }

  .van-popup--center.van-popup--round > > > .bet p {
    color: #adadad;
  }

  .notice {
    font-size: 28px;
    margin: 40px 0 20px;
  }

  .notice span {
    color: orangered;
    font-size: 32px;
    font-weight: 800;
    margin-left: 4px;
  }

  .config {
    background-color: orangered;
    color: white;
    border-radius: 8px;
    height: 80px;
    width: 70%;
    margin: 40px auto 30px;
    display: block;
    font-size: 32px;
  }

  .coin > > > .van-popup.van-popup--center {
    transform: translate3d(-50%, 2%, 0);
    width: 100%;
    top: 60%;
  }

  .Recharge {
    font-size: 28px;
    padding: 12px;
    border-bottom: 2px solid #e4e4e4;
    display: flex;
    align-items: center;
  }

  .Recharge input {
    width: 60%;
    background: #fff;
    margin-left: 0.2rem;
  }

  .Recharge input::placeholder {
    padding-left: 0.5rem;
  }

  .coin .list li div:last-child {
    padding: 0px !important;
    font-weight: 500;
  }

  .bet span:last-child {
    font-size: 24px;
  }

  .van-picker {
    margin-top: 45px;
  }

  .noData {
    width: 100%;
    text-align: center;
    display: block;
    margin-top: 20px;
  }

  .bet {
    margin-bottom: 0px !important;
  }
</style>
